$(function() {
  'use strict';

  var map = new BMap.Map('map', {enableMapClick: false});

  map.centerAndZoom(new BMap.Point(105.403119, 38.028658), 5);
  map.enableScrollWheelZoom(true);

  map.setMapStyle({
    styleJson: [
      {
        "featureType": "water",
        "elementType": "all",
        "stylers": {
          "color": "#021019"
        }
      }, {
        "featureType": "highway",
        "elementType": "geometry.fill",
        "stylers": {
          "color": "#000000"
        }
      }, {
        "featureType": "highway",
        "elementType": "geometry.stroke",
        "stylers": {
          "color": "#147a92"
        }
      }, {
        "featureType": "arterial",
        "elementType": "geometry.fill",
        "stylers": {
          "color": "#000000"
        }
      }, {
        "featureType": "arterial",
        "elementType": "geometry.stroke",
        "stylers": {
          "color": "#0b3d51"
        }
      }, {
        "featureType": "local",
        "elementType": "geometry",
        "stylers": {
          "color": "#000000"
        }
      }, {
        "featureType": "land",
        "elementType": "all",
        "stylers": {
          "color": "#08304b"
        }
      }, {
        "featureType": "railway",
        "elementType": "geometry.fill",
        "stylers": {
          "color": "#000000"
        }
      }, {
        "featureType": "railway",
        "elementType": "geometry.stroke",
        "stylers": {
          "color": "#08304b"
        }
      }, {
        "featureType": "subway",
        "elementType": "geometry",
        "stylers": {
          "lightness": -70
        }
      }, {
        "featureType": "building",
        "elementType": "geometry.fill",
        "stylers": {
          "color": "#000000"
        }
      }, {
        "featureType": "all",
        "elementType": "labels.text.fill",
        "stylers": {
          "color": "#857f7f"
        }
      }, {
        "featureType": "all",
        "elementType": "labels.text.stroke",
        "stylers": {
          "color": "#000000"
        }
      }, {
        "featureType": "building",
        "elementType": "geometry",
        "stylers": {
          "color": "#022338"
        }
      }, {
        "featureType": "green",
        "elementType": "geometry",
        "stylers": {
          "color": "#062032"
        }
      }, {
        "featureType": "boundary",
        "elementType": "all",
        "stylers": {
          "color": "#1e1c1c"
        }
      }, {
        "featureType": "manmade",
        "elementType": "geometry",
        "stylers": {
          "color": "#022338"
        }
      }, {
        "featureType": "poi",
        "elementType": "all",
        "stylers": {
          "visibility": "off"
        }
      }, {
        "featureType": "all",
        "elementType": "labels.icon",
        "stylers": {
          "visibility": "off"
        }
      }, {
        "featureType": "all",
        "elementType": "labels.text.fill",
        "stylers": {
          "color": "#2da0c6",
          "visibility": "on"
        }
      }
    ]
  });

  var menu = new BMap.ContextMenu();

  var txtMenuItem = [
		{
			text:'重置',
			callback: function(){

      }
		},
		{
			text:'框选',
			callback: function(){
        drawingManager.open();
      }
		}
	];

  for(var i=0; i < txtMenuItem.length; i++){
		menu.addItem(new BMap.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback, 100));
	}

	map.addContextMenu(menu);

  var options = {
    fillStyle: 'rgba(255, 240, 50, 0.2)',
    shadowColor: 'rgba(255, 240, 50, 0.2)',
    shadowBlur: 20,
    globalCompositeOperation: 'lighter',
    size: 3,
    draw: 'simple',
    animation: {
      type: 'time',
      stepsRange: {
        start: 0,
        end: 10
      },
      trails: 2.5,
      duration: 1
    }
  }

  var DataOptions = {
    fillStyle: 'rgba(255, 240, 50, 0.6)',
    globalCompositeOperation: 'lighter',
    methods: {
      click: function(item) {
        if (!item) {
          return
        }
        map.enableDragging();
      },
      mousemove: function(item) {
        if (!item) {
          $('#info_pop').hide()
          return
        }

        // console.log(item);

        var pop = $('#info_pop');
        if (!pop.length) {
          pop = $('<div id="info_pop"></div>');
          $('#map').append(pop);
        }

        pop.show().html('导游：' + item.daoyou_name).css({
          top: item.geometry._coordinates[1] + 5,
          left: item.geometry._coordinates[0] + 5
        })

      }
    },
    size: 2,
    draw: 'simple'
  };




  var init = function() {
    fetchData();
  };

  /**
   * 获取去数据
   */
  var fetchData = function () {
    $.post('task', {time: Date.now()}, function(result) {
      var data = JSON.parse(result);

      renderData(data)
    })

    setTimeout(fetchData, 160*1000)
  }

  var dataSet, mapvLayer, mapvdata, mainData;

  /**
   * 渲染数据到视图
   */
  var renderData = function (res) {
    mainData = res.data;

    if (!dataSet) {
      dataSet = new mapv.DataSet(mainData);
      mapvLayer = new mapv.baiduMapLayer(map, dataSet, options);
      mapvdata = new mapv.baiduMapLayer(map, dataSet, DataOptions);
      return
    }

    dataSet.set(mainData);
  }


  // 框选
  var overlaycomplete = function(e){
      ptInRect(e.overlay)
  };

  var styleOptions = {
      strokeColor:"red",    //边线颜色。
      fillColor:"red",      //填充颜色。当参数为空时，圆形将没有填充效果。
      strokeWeight: 3,       //边线的宽度，以像素为单位。
      strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
      fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
      strokeStyle: 'solid' //边线的样式，solid或dashed。
  }

  //实例化鼠标绘制工具
  var drawingManager = new BMapLib.DrawingManager(map, {
      isOpen: false, //是否开启绘制模式
      enableDrawingTool: false, //是否显示工具栏
      rectangleOptions: styleOptions //矩形的样式
  });

  drawingManager.setDrawingMode(BMAP_DRAWING_RECTANGLE);
  drawingManager.addEventListener('overlaycomplete', overlaycomplete);

  $('#kuang_ctl').on('click', function() {
    $(this).addClass('active');
    drawingManager.open();
  })


  /**
   * 获取多边形内部的点
   */
  var ptInRect = function (overlay) {
    var ply = new BMap.Polygon(overlay.no);

    var selectPoint = [];
    var data = dataSet.get().map(function(item) {
      var p = item.geometry.coordinates;
      var point = new BMap.Point(p[0], p[1])

      if (BMapLib.GeoUtils.isPointInPolygon(point, ply)) {
        item._point = point;
        item.fillStyle = '#e0f173';
        item.size = 6;
        item.shadowColor = 'rgba(0,0,0,0)';
        selectPoint.push(item)
      }

      return item
    });

    dataSet.set(data);

    console.log(selectPoint)

    // 设置可视区域
    var view = map.getViewport(overlay.no);

    map.centerAndZoom(view.center, view.zoom - 1);
    mapvLayer.destroy();
    mapvLayer = new mapv.baiduMapLayer(map, dataSet, options);
    map.removeOverlay(overlay);
    drawingManager.close();
  };

  

  init();
});
